import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.escape import json_encode, json_decode 
from tornado.options import define, options
define("port", default = 8888, help="run on the given port", type = int)

from urlparse import urlparse
from match import *
from team import *

import urllib


class BaseHandler(tornado.web.RequestHandler):
	def get(self):
		self.render("index.html")

def parseURL(url):
	list1= [part.split('=') for part in url.split('&')]
	params = dict([(x,y) for x, y in list1 if y != ""])
	return params	

class MatchHandler(tornado.web.RequestHandler):
	def get(self):
		url = self.request.uri
		url = url[9:]
		#self.write(url)
		params = parseURL(url)
		method = params.get('method',"GetInfoOfMatch")
		IDMatch = params.get('IDMatch')
		date = urllib.unquote(params.get('date',""))
		IDLeague = params.get('IDLeague',-1)
											
		if method == "GetInfoOfMatch":
			infoMatch = GetInfoOfMatch(IDMatch)
			self.write(json_encode(unicode(infoMatch)))		
		elif method == "GetSquadOfMatch":
			squad = GetSquadOfMatch(IDMatch)
			self.write(json_encode(unicode(squad)))		
		elif method == "GetHighlightOfMatch":
			highlight = GetHighlightOfMatch(IDMatch)
			self.write(json_encode(unicode(highlight)))		
		elif method == "GetListOfMatch":
			listOfMatch = GetListOfMatch(date, IDLeague)
			self.write(json_encode(unicode(listOfMatch)))				


class TeamHandler(tornado.web.RequestHandler):
	def get(self):
		url = self.request.uri
		url = url[7:]
		#self.write(url)
		params = parseURL(url)
		method = params.get('method',"GetInfoTeam")
		IDTeam = params.get('IDTeam')
		if method == "GetInfoTeam":
			result = GetInfoTeam(IDTeam)
			self.write(json_encode(unicode(result)))				
def main():
	tornado.options.parse_command_line()
	application = tornado.web.Application([
		(r"/", BaseHandler),		
		(r"/matches", MatchHandler),
		(r"/teams", TeamHandler),		
	])

	http_server = tornado.httpserver.HTTPServer(application)
	http_server.listen(options.port)
	tornado.ioloop.IOLoop.instance().start()


if __name__ == '__main__':
	main()

